package com.pdh.front.controller;

import com.pdh.bean.Message;
import com.pdh.bean.User;
import com.pdh.mvc.ResponseBody;
import com.pdh.service.CourierService;
import com.pdh.service.UserService;
import com.pdh.util.JSONUtil;
import com.pdh.util.LoginUtil;
import com.pdh.util.RandomUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 彭德华
 * @Date 2021-08-29 22:19
 */
public class UserController {
    /**
     * 获取验证码短信（验证码已封装到message返回）
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/front/userLoginSms.do")
    public String sendSms(HttpServletRequest req, HttpServletResponse resp){
        String userPhone = req.getParameter("userPhone");
        //拿到code值
        String authCode = RandomUtil.getCode() + "";//发短信就用 用户接收到后需要填入
        //boolean flag = SMSUtil.loginSMS(userPhone, authCode);//发送短信
        //这里模拟发送短信成功
        boolean flag = true;
        Message msg = null;
        if(flag){ //短信发送成功
            //使用会话存储信息(存储了以手机号码和验证码的键值对) 后面可以进行对比验证码是否正确
            LoginUtil.setLoginSms(req.getSession(), userPhone, authCode);
            //这里本不该传递验证码，但是因为不能发送短信，就把验证码传到前台
            msg = new Message(0,"验证码已发送,请查收",authCode);
        }else { //短信发送失败
            msg = new Message(-1,"验证码发送失败,请稍后再试");
        }
        String json = JSONUtil.toJSON(msg);
        System.out.println(json);
        return json;
    }

    /**
     * 登陆
     * 这里处理的逻辑是获取到手机号和验证码，首先判断验证码是否和之前存储在session里面的一致
     * 之后就是判断此号码是用户还是快递员
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/front/login.do")
    public String login(HttpServletRequest req, HttpServletResponse resp){
        String userPhone = req.getParameter("userPhone");
        String userAuthCode = req.getParameter("userAuthCode");
        //todo 密码登陆
        String password = req.getParameter("password");
        String authCode = LoginUtil.getLoginSmsAuthCode(req.getSession(), userPhone);
        Message msg = null;
        if(authCode == null){
            //手机号未获取短信
            msg = new Message(-1,"手机号码未获取短信");
        }else if(authCode.equals(userAuthCode)){
            //用户提供的code于系统存储的验证码一致 登录成功
            Message flagCourierLogin = CourierService.login(userPhone);
            Message flagUserLogin = UserService.login(userPhone);
            boolean isCourier = false;
            // TODO 这个判断应替换为快递员表格查询手机号的结果
            if(flagCourierLogin.getStatus() == 0){//有查询到
                //快递员
                isCourier = true;
                String ip = req.getRemoteAddr();
                CourierService.updateLoginInformation(userPhone,ip);
                msg = new Message(0,"快递员登陆成功",isCourier);
            }
            if(flagUserLogin.getStatus() == 0){
                //用户
                String ip = req.getRemoteAddr();
                UserService.updateLoginInformation(userPhone,isCourier,ip);
                msg = new Message(0,"登陆成功",isCourier);
            }
            if(msg == null){
                //该用户第一次登陆 用户注册并执行登陆
                User newUser = new User(null, null, userPhone ,null);
                Message userRegFlag = UserService.insert(newUser);
                if(userRegFlag.getStatus() == 0){
                    //注册成功
                    String ip = req.getRemoteAddr();
                    UserService.updateLoginInformation(userPhone,false,ip);
                    msg = new Message(0,"用户注册成功！");
                }
            }
            //使用session存储用户号码，过滤器获取不到则认为未执行
            User user =  (User) UserService.findByUserPhone(userPhone).getData();
            LoginUtil.setFrontUser(req.getSession(),user);
        }else {
            //用户提供的code于系统存储的验证码不一致 登录失败
            msg = new Message(-2,"验证码不一致,请检查");
        }
        String json = JSONUtil.toJSON(msg);
        return json;//status有 -1 -2 1 0 四个状态
    }

    /**
     * 退出登录（session删除、用户更改）
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/front/userLogout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp){
        Message msg =null;
        User user = (User) req.getSession().getAttribute("frontUser");
        msg = UserService.logout(user.getId());

        //1.invalidate() 销毁session
        req.getSession().invalidate();
        //2.给客户端回复消息
        return  JSONUtil.toJSON(msg);
    }

    /**
     * 判断用户是不是快递员
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/front/userInfo.do")
    public String userInfo(HttpServletRequest req, HttpServletResponse resp){
        User user = LoginUtil.getFrontUser(req.getSession());
        Message message = new Message(0,"获取用户信息成功",user);
        String json = JSONUtil.toJSON(message);
        return json;
    }

}
